const router = require('koa-router')()
const db = require('../utils/db')
const multer = require('@koa/multer')
const fs = require('fs')
const path = require('path')
router.prefix('/users')

// 配置文件上传
const storage = multer.diskStorage({
    // 创建文件存放的目录
    destination: function (req, file, cb) {
        try {
            fs.statSync(path.join(__dirname, '../public/upload-files'))
        } catch (e) {
            fs.mkdirSync('./public/upload-files')
        }
        cb(null, './public/upload-files')
    },
    filename: function (req, file, cb) {
        const ext = file.originalname.split('.').pop()
        cb(null, file.fieldname + '-' + Date.now() + '.' + ext)
    }
})

const upload = multer({
    storage,
})
// 配置文件上传

router.get('/', async function (ctx) {
    ctx.body = 'users'
})

// 文件上传（修改头像）
router.post('/upload-avatar', upload.single('avatar'), async ctx => {
    const { id } = ctx.request.body
    if (!id) {
        ctx.body = db.doResponse({ message: '用户头像上传成功', data: ctx.request.file })
        return
    }
    const sql = 'update users set avatar=? where id=?'
    const params = [ctx.request.file.filename, id]
    const r = await db.doSQL(sql, params)
    if (r.affectedRows > 0) {
        ctx.body = db.doResponse({ message: '用户头像上传成功', data: r })
    } else {
        ctx.body = db.doResponse({ success: false, errorCode: 4004, message: '用户头像上传失败', data: r })
    }
})

// 用户列表、搜索、分页、排序
router.get('/user-list', async ctx => {
    const { currentPage = 0, pageSize = 10, sortBy = "id", order = 'asc', query } = ctx.query
    let sql = `select * from users`

    // 搜索
    if (query) {
        sql += ` where name like '%${query}%'`
    }

    // 排序
    if (order) {
        sql += ` order by ${sortBy} ${order}`
    }

    // 分页
    sql += ` limit ${currentPage * pageSize},${pageSize}`
    const r = await db.doSQL(sql)
    // 获取总条数
    let totalSql = `select count(*) as total from users`
    if (query) {
        totalSql += ` where name like '%${query}%'`
    }
    const totalR = await db.doSQL(totalSql)
    const total = totalR[0].total
    ctx.body = db.doResponse({ message: '获取用户成功', total, data: r })
})

// 删除用户
router.get('/delete-user', async ctx => {
    const { id } = ctx.query
    const sql = `delete from users where id in (${id})`
    const params = [id]
    const r = await db.doSQL(sql, params)
    if (r.affectedRows > 0) {
        ctx.body = db.doResponse({ message: '删除用户成功', data: r })
    } else {
        ctx.body = db.doResponse({ success: false, errorCode: 4003, message: '删除用户失败', data: r })
    }
})

// 修改用户
router.post('/update-user', async ctx => {
    const { name, age, gender, loginName, loginKey, avatar, id } = ctx.request.body
    const sql = 'update users set name=?, age=?, gender=?, loginName=?, loginKey=?,avatar=? where id=?'
    const params = [name, age, gender, loginName, loginKey, avatar, id]
    const r = await db.doSQL(sql, params)
    if (r.affectedRows > 0) {
        ctx.body = db.doResponse({ message: '修改用户成功', data: r })
    } else {
        ctx.body = db.doResponse({ success: false, errorCode: 4002, message: '修改用户失败', data: r })
    }
})

// 新增用户
router.post('/save-user', async ctx => {
    const { name, age, gender, loginName, loginKey, avatar } = ctx.request.body
    const sql = 'insert into users (name,age,gender,loginName,loginKey,avatar) values (?,?,?,?,?,?)'
    const params = [name, age, gender, loginName, loginKey, avatar]
    const r = await db.doSQL(sql, params)
    if (r.affectedRows > 0) {
        ctx.body = db.doResponse({ message: '新增用户成功', data: r })
    } else {
        ctx.body = db.doResponse({ success: false, errorCode: 4001, message: '新增用户失败', data: r })
    }
})

module.exports = router